<!-- 活动签到记录管理 -->
<template>
  <div class="record-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title">
        <el-icon><Calendar /></el-icon>
        <span>活动签到记录</span>
      </div>
      <div class="header-actions">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>补录签到
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动ID">
          <el-input v-model="searchForm.activityId" placeholder="请输入活动ID" clearable />
        </el-form-item>
        <el-form-item label="志愿者ID">
          <el-input v-model="searchForm.volunteerId" placeholder="请输入志愿者ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 160px">
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已驳回" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 160px">
            <el-option label="正常签到" :value="0" />
            <el-option label="补录" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="activityId" label="活动ID" width="80" align="center" />
        <el-table-column prop="volunteerName" label="志愿者" width="80" align="center" show-overflow-tooltip />
        <el-table-column label="签到时间" width="160" align="center">
          <template #default="scope">
            {{ scope.row.signInTime }}
          </template>
        </el-table-column>
        <el-table-column label="签退时间" width="160" align="center">
          <template #default="scope">
            {{ scope.row.signOutTime }}
          </template>
        </el-table-column>
        <el-table-column prop="serviceDuration" label="服务时长" width="80" align="center">
          <template #default="scope">
            {{ scope.row.serviceDuration }} 小时
          </template>
        </el-table-column>
        <el-table-column prop="location" label="签到地点" min-width="80" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="dark">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.type === 0 ? 'success' : 'warning'" effect="plain">
              {{ scope.row.type === 0 ? '正常签到' : '补录' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button 
              type="success" 
              link 
              @click="handleReview(scope.row)"
              v-if="scope.row.status === 0"
            >
              <el-icon><Check /></el-icon>审核
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
              v-if="scope.row.status !== 1"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 补录对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="isView"
      >
        <el-form-item label="活动ID" prop="activityId">
          <el-input v-model="form.activityId" placeholder="请输入活动ID" />
        </el-form-item>
        <el-form-item label="志愿者ID" prop="volunteerId">
          <el-input v-model="form.volunteerId" placeholder="请输入志愿者ID" />
        </el-form-item>
        <el-form-item label="志愿者姓名" prop="volunteerName">
          <el-input v-model="form.volunteerName" placeholder="请输入志愿者姓名" />
        </el-form-item>
        <el-form-item label="签到时间" prop="signInTime">
          <el-date-picker
            v-model="form.signInTime"
            type="datetime"
            placeholder="请选择签到时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="签退时间" prop="signOutTime">
          <el-date-picker
            v-model="form.signOutTime"
            type="datetime"
            placeholder="请选择签退时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="签到地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入签到地点" />
        </el-form-item>
        <el-form-item label="补录说明" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            placeholder="请输入补录说明" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="!isView">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      title="审核签到记录"
      v-model="reviewDialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          label="驳回原因" 
          prop="rejectReason"
          v-if="reviewForm.status === 2"
        >
          <el-input 
            v-model="reviewForm.rejectReason" 
            type="textarea" 
            placeholder="请输入驳回原因" 
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReviewSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Calendar,
  Plus, 
  Search, 
  Refresh, 
  Edit, 
  View, 
  Delete,
  Check
} from '@element-plus/icons-vue'
import { 
  getRecordList,
  addRecord,
  deleteRecord,
  batchDeleteRecord,
  reviewRecord,
  getRecordDetail
} from '@/api/record'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  activityId: '',
  volunteerId: '',
  status: null,
  type: null
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const isView = ref(false)

// 表单数据
const form = reactive({
  activityId: '',
  volunteerId: '',
  volunteerName: '',
  signInTime: '',
  signOutTime: '',
  location: '',
  remark: ''
})

// 表单验证规则
const rules = {
  activityId: [{ required: true, message: '请输入活动ID', trigger: 'blur' }],
  volunteerId: [{ required: true, message: '请输入志愿者ID', trigger: 'blur' }],
  volunteerName: [{ required: true, message: '请输入志愿者姓名', trigger: 'blur' }],
  signInTime: [{ required: true, message: '请选择签到时间', trigger: 'change' }],
  signOutTime: [{ required: true, message: '请选择签退时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入签到地点', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入补录说明', trigger: 'blur' }]
}

// 审核对话框相关
const reviewDialogVisible = ref(false)
const reviewFormRef = ref(null)
const reviewForm = reactive({
  id: '',
  status: 1,
  rejectReason: '',
  reviewerId: 1 // TODO: 从用户信息中获取
})

// 审核表单验证规则
const reviewRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  rejectReason: [{ 
    required: true, 
    message: '请输入驳回原因', 
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (reviewForm.status === 2 && !value) {
        callback(new Error('请输入驳回原因'))
      } else {
        callback()
      }
    }
  }]
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',   // 待审核
    1: 'success',   // 已审核
    2: 'danger'     // 已驳回
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已审核',
    2: '已驳回'
  }
  return texts[status] || '未知'
}

// 获取签到记录列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await getRecordList(params)
    if (res.code === 200) {
      tableData.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.message || '获取签到记录列表失败')
    }
  } catch (error) {
    console.error('获取签到记录列表失败：', error)
    ElMessage.error('获取签到记录列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = null
  })
  handleSearch()
}

// 表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  isView.value = false
  resetForm()
}

// 新增补录
const handleAdd = () => {
  dialogTitle.value = '补录签到记录'
  dialogVisible.value = true
  isView.value = false
  resetForm()
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getRecordDetail(row.id)
    if (res.code === 200) {
      dialogTitle.value = '查看签到记录'
      dialogVisible.value = true
      isView.value = true
      Object.keys(form).forEach(key => {
        form[key] = res.data[key] || ''
      })
    } else {
      ElMessage.error(res.message || '获取签到记录详情失败')
    }
  } catch (error) {
    console.error('获取签到记录详情失败：', error)
    ElMessage.error('获取签到记录详情失败')
  }
}

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该签到记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRecord(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '删除签到记录失败')
      }
    } catch (error) {
      console.error('删除签到记录失败：', error)
      ElMessage.error('删除签到记录失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  // 检查是否包含已审核的记录
  if (selectedRows.value.some(row => row.status === 1)) {
    ElMessage.warning('选中的记录中包含已审核的记录，不允许删除')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const res = await batchDeleteRecord({ ids })
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '批量删除记录失败')
      }
    } catch (error) {
      console.error('批量删除记录失败：', error)
      ElMessage.error('批量删除记录失败')
    }
  })
}

// 审核记录
const handleReview = (row) => {
  reviewForm.id = row.id
  reviewForm.status = 1
  reviewForm.rejectReason = ''
  reviewDialogVisible.value = true
}

// 提交审核
const handleReviewSubmit = async () => {
  if (!reviewFormRef.value) return
  await reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await reviewRecord(reviewForm)
        if (res.code === 200) {
          ElMessage.success('审核成功')
          reviewDialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error(res.message || '审核失败')
        }
      } catch (error) {
        console.error('审核失败：', error)
        ElMessage.error('审核失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addRecord(form)
        if (res.code === 200) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error(res.message || '保存签到记录失败')
        }
      } catch (error) {
        console.error('保存签到记录失败：', error)
        ElMessage.error('保存签到记录失败')
      }
    }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.record-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title .el-icon {
  font-size: 28px;
  margin-right: 12px;
  color: #fff;
}

.search-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.table-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

:deep(.el-table) {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #262626;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
  color: #595959;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-button--link) {
  padding: 0 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--link:hover) {
  transform: translateY(-1px);
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px 32px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #262626;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #d9d9d9 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.text-gray-500 {
  color: #666;
}
</style> 